﻿using System;
using System.Windows.Forms;
using NanoERP.Infrastructure;
using NanoERP.Business.BaseInfo;
using DevComponents.AdvTree;
using NanoERP.Model;
using System.Collections.Generic;
using NanoERP.Common;
using NanoERP.Properties;

namespace NanoERP.BaseInfo
{
    //[Module("FrmSelectStaff")]
    public partial class FrmSelectStaff : ModuleForm
    {
        readonly DeptinfoBLL _deptinfobLl;
        readonly UserinfoBLL _userinfobll;
        readonly Dictionary<long, string> _dicUserInfo;
        private const string SeletedCell = "SELECTED";
        readonly bool _isCheckBoxCell;
        public FrmSelectStaff()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 职员选择
        /// </summary>
        /// <param name="isCheckBoxCell">是否显示选择列</param>
        public FrmSelectStaff(bool isCheckBoxCell = false)
        {
            InitializeComponent();

            _userinfobll = new UserinfoBLL();
            _deptinfobLl = new DeptinfoBLL();
            _dicUserInfo = new Dictionary<long, string>();
            _isCheckBoxCell = isCheckBoxCell;

            BindTreeView();
            dgvList.Columns[SeletedCell].Visible = isCheckBoxCell;
        }

        /// <summary>
        /// 
        /// </summary>
        void QueryDepartUser()
        {
            if (dicTree.SelectedNode == null) return;
            var id = int.Parse(dicTree.SelectedNode.Name);
            dgvList.AutoGenerateColumns = false;
            dgvList.DataSource = _userinfobll.Query(id, txtKey.Text.Trim());
        }

        /// <summary>
        /// 绑定部门树
        /// </summary>
        void BindTreeView()
        {
            dicTree.Nodes.Clear();

            var firNode = new Node("所有部门") { Tag = new Deptinfo { Deptname = "所有部门", Parentdeptid = 0 }, Name = "0", Image = Resources.XmlStructure };
            firNode.ExpandAll();
            var firList = _deptinfobLl.Query(0);
            RecursiveLoopNodes(firList, firNode);

            dicTree.Nodes.Add(firNode);
            if (dicTree.Nodes.Count > 0)
                dicTree.SelectedNode = dicTree.Nodes[0].Nodes.Count > 0 ? dicTree.Nodes[0].Nodes[0] : dicTree.Nodes[0];
        }

        /// <summary>
        /// 递归循环调用
        /// </summary>
        /// <param name="firList">一级树集合</param>
        /// <param name="parentNode">上级节点</param>
        void RecursiveLoopNodes(List<Deptinfo> firList, Node parentNode)
        {
            firList.ForEach(r =>
            {
                var secNode = new Node(r.Deptname) { Tag = r, Name = r.Id.ToString(), Image = Resources.CreateTableTemplatesGallery };

                parentNode.Nodes.Add(secNode);
                var recList = _deptinfobLl.Query(r.Id);
                if (recList.Count > 0)
                    RecursiveLoopNodes(recList, secNode);
            });
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (_isCheckBoxCell && _dicUserInfo.Count == 0)
            {
                MessageBox.Show(@"没有选择人员，请重新检索后选择记录！", @"提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }

            if (!_isCheckBoxCell)
            {
                if (dgvList.CurrentRow == null)
                {
                    MessageBox.Show(@"没有选择人员，请重新检索后选择记录！", @"提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }

                var vv = dgvList.CurrentRow.DataBoundItem as Userinfo;
                _dicUserInfo.Add(vv.Id, vv.Username);
            }

            this.Tag = _dicUserInfo;
            this.DialogResult = DialogResult.OK;
        }

        private void dicTree_AfterNodeSelect(object sender, AdvTreeNodeEventArgs e)
        {
            QueryDepartUser();
        }

        private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;

            if (dgvList.CurrentCell.OwningColumn.Name == SeletedCell)
                return;

            btnSelect_Click(null, null);
        }

        private void dgvList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            ControlUtil.DataGridRowPostPaint(sender, e);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            var obj = dicTree.SelectedNode.Tag as Deptinfo;

            var f = new FrmDepartStaff(obj);
            if (f.ShowDialog() == DialogResult.OK)
            {
                QueryDepartUser();
            }
        }

        private void txtKey_TextChanged(object sender, EventArgs e)
        {
            QueryDepartUser();
        }

        private void dgvList_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dgvList.IsCurrentCellDirty) dgvList.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void dgvList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;

            if (dgvList.Columns[e.ColumnIndex].Name == SeletedCell)
            {
                var currRow = dgvList.Rows[e.RowIndex];
                var checkCell = (DataGridViewCheckBoxCell)currRow.Cells[SeletedCell];
                var vv = currRow.DataBoundItem as Userinfo;

                if (checkCell.Value.Equals("1"))
                    _dicUserInfo.Add(vv.Id, vv.Username);
                else
                    _dicUserInfo.Remove(vv.Id);

                dgvList.Invalidate();
            }
        }
    }
}
